package com.rpt

import com.beans.AdLog
import com.dmp.RptUtils
import org.apache.commons.lang.StringUtils
import org.apache.hadoop.fs.{FileSystem, Path}
import org.apache.spark.{SparkConf, SparkContext}

/**
  * ClassName:MediaAnalyseRpt
  * Package:com.dmp
  * Desciption:
  *
  * @date:2019 /8/23 22:28
  * @author:17611219021 @sina.cn
  */
object MediaAnalyseRpt {
  def main(args: Array[String]): Unit = {
    if(args.length !=3){
      println(
        """
          |com.dmp.fileToParquet
          |参数：
          | inputpath
          | outputPath
          | directPath
        """.stripMargin)
      sys.exit()
    }
    val sparkConf = new SparkConf()
    sparkConf.setAppName(s"${this.getClass.getSimpleName}")
    sparkConf.setMaster("local[*]")
    //指定keyo序列化器与snappy格式，默认是gzip格式
    sparkConf.set("spark.serializer","org.apache.spark.serializer.KryoSerializer")
    sparkConf.set("spark.sql.parquet.compression.codec","snappy")
    val sc: SparkContext = new SparkContext(sparkConf)
    val Array(inputpath,outputPath,directPath)= args

    val configuration = sc.hadoopConfiguration
    val fs = FileSystem.get(configuration)
    val path = new Path(outputPath)
    if(fs.exists(path)){
      fs.delete(path,true)
    }

    //字典文件
    val directdata = sc.textFile(directPath)
    val directMap = directdata.map(line => {
      val fieds = line.split(",", -1)
      (fieds(0), fieds(1))
    }).collect().toMap
    val broadcast = sc.broadcast(directMap)

    sc.textFile(inputpath).map(_.split(",",-1)).filter(_.length>=3).map(
      arr=>{
       val adlog= AdLog(arr)
        var newappname=adlog.appname
        println(newappname+"===="+StringUtils.isEmpty(newappname))

        if("".equals(newappname.trim)){
          newappname = broadcast.value.getOrElse(adlog.appid,"UnkownMediaAPP")
        }
        //原始请求、有效请求、广告请求
        val listReq = RptUtils.calculateReq(adlog.requestmode,adlog.processnode)

        //参与竞价、竞价成功、消费、成本
        val listRtb = RptUtils.calculateRtb(adlog.iseffective,adlog.isbiding,adlog.isbid,adlog.adorderid,adlog.iswin,adlog.adpayment,adlog.winprice)

        //广告展示、广告点击
        val listShowOrClick = RptUtils.calculateShowOrClick(adlog.requestmode,adlog.iseffective)
        (newappname,listReq++listRtb++listShowOrClick)
      }).reduceByKey((list1,list2) =>{
      list1.zip(list2).map(t=>{t._1+t._2})
    }).saveAsTextFile(outputPath)
    sc.stop()


  }

}
